package ru.rchervot.sanasar.client.view;

import ru.rchervot.sanasar.client.event.EventRPCStatus;
import ru.rchervot.sanasar.client.event.HandlerRPCStatus;

import com.google.gwt.event.shared.HandlerManager;
import com.google.inject.Inject;

public class ConnectionInfoPresenterDefault implements ConnectionInfoPresenter {
	
	private final Display display;
	private final HandlerManager eventBus;
	
	@Inject
	public ConnectionInfoPresenterDefault(Display display, 
			HandlerManager eventBus) {
		this.display = display;
		this.eventBus = eventBus;
		
		listenForRPCStatusChange();
	}
	
	@Override
	public void bindDisplay() {
		display.setPresenter(this);
	}
	
	private void listenForRPCStatusChange() {
		eventBus.addHandler(EventRPCStatus.getType(),
				new HandlerRPCStatus() {
			@Override
			public void onStatusChange(EventRPCStatus event) {
				processNewStatus(event.getStatus());
			}
		});
	}
	
	private int numberOfLoadingRequests = 0;
	
	private void processNewStatus(EventRPCStatus.Status status) {
		switch(status) {
		case LOADING: 
			numberOfLoadingRequests++; 
			display.showRPCStatusLoading();
		break;
		case SUCCESS: 
			numberOfLoadingRequests--;
			if (numberOfLoadingRequests == 0) display.hideRPCStatus();
			break;
		case FAILURE: 
			numberOfLoadingRequests = 0; 
			display.showRPCStatusFailure();
			break;
		}
		
		System.out.println("numberOfLoadingRequests: " + numberOfLoadingRequests);
	}
	
}
